#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

check_affinity() {
    local cluster="$1"
    local skip_wait=$2

    # apply cr config
    apply_config "$test_dir/conf/$cluster.yml"

    # check if at least 1 Pod started
    if [ -z "$skip_wait" ]; then
        wait_for_running $cluster-pxc 1
    else
        sleep 5
    fi

    # check if statefulset created with expected config
    compare_kubectl statefulset/$cluster-pxc
    compare_kubectl statefulset/$cluster-proxysql

    # delete cluster
    kubectl_bin delete \
        -f $test_dir/conf/$cluster.yml
}

main() {
    create_infra $namespace
    kubectl_bin apply -f $conf_dir/secrets.yml

    desc 'check hostname anti-affinity'
    check_affinity "hostname"

    desc 'check zone anti-affinity'
    check_affinity "zone"

    desc 'check region anti-affinity'
    check_affinity "region"

    desc 'check custom anti-affinity'
    check_affinity "custom" "skip_wait"

    destroy $namespace
}

main
